package com.demo.androidtv;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.demo.androidtv.adapter.BookListAdapter;
import com.demo.androidtv.bean.Book;
import com.demo.androidtv.fragment.BookDetailFragment;
import com.demo.androidtv.utils.ModelUtil;
import com.demo.androidtv.utils.WebSocketTool;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity implements Handler.Callback, BookListAdapter.OnItemClickListener {
    private final static int RETURN_TO_HOME_DELAY_SHORT = 5000; // 5 second
    private final static int RETURN_TO_HOME_DELAY = 15000; // 15 second
    private final static int RETURN_TO_HOME = 0x700;
    private final static int SHOW_RESULT = 0x701;

    private final static int HIDE_NAVIGATION = 0x20;

    @ViewInject(R.id.ll_home)
    private View llHome;
    @ViewInject(R.id.ll_not_found_result)
    private View llNotFoundResult;
    @ViewInject(R.id.ll_found_result)
    private View llFoundResult;
    @ViewInject(R.id.list_book)
    private RecyclerView listBook;

    private Map<String, Book> bookResult = new LinkedHashMap<>();

    private Messenger messenger;

    private BookDetailFragment fragment;
    private BookListAdapter adapter;

    private boolean isOnReConnect = false;

    private Handler UIHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        x.view().inject(this);

        UIHandler = new Handler(this);

        UIHandler.sendEmptyMessage(HIDE_NAVIGATION);

        bookResult.putAll(ModelUtil.getBooks());

        adapter = new BookListAdapter(this);
        adapter.setOnItemClickListener(this);

        listBook.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        listBook.setAdapter(adapter);

        messenger = new Messenger(new Handler(this));
        WebSocketTool.RegisterMessageCallback(messenger);
    }

    private void hideNavigation() {
        if (Build.VERSION.SDK_INT < 16) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE;
        decorView.setSystemUiVisibility(uiOptions);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, 0, 1, "重新连接");
//        menu.add(Menu.NONE, 1, 2, "设置别名");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                isOnReConnect = true;
                WebSocketTool.Disconnect();
                break;
            case 1:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        WebSocketTool.RemoveMessageCallback(messenger);
        messenger = null;
        super.onDestroy();
    }

    @Override
    public void onItemClick(int position) {
        adapter.setItemSelectedEntity(position);

        Book book = adapter.getItem(position);
        fragment.setData(book);

        UIHandler.sendEmptyMessage(SHOW_RESULT);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case HIDE_NAVIGATION:
                UIHandler.sendEmptyMessageDelayed(HIDE_NAVIGATION, 2000);
                hideNavigation();
                break;
            case RETURN_TO_HOME:
                showHome();
                return true;
            case SHOW_RESULT:
                UIHandler.removeMessages(RETURN_TO_HOME);

                llHome.setVisibility(View.INVISIBLE);
                llFoundResult.setVisibility(View.VISIBLE);
                llNotFoundResult.setVisibility(View.INVISIBLE);

                UIHandler.sendEmptyMessageDelayed(RETURN_TO_HOME, RETURN_TO_HOME_DELAY);
                return true;
            case WebSocketTool.TYPE_CONNECT:
                Log.d("Message Type", "TYPE_CONNECT");
                Toast.makeText(this, "已经连接到服务器", Toast.LENGTH_SHORT).show();
                isOnReConnect = false;
                break;
            case WebSocketTool.TYPE_DISCONNECT:
                Log.d("Message Type", "TYPE_DISCONNECT");
                Toast.makeText(this, "和服务器断开连接", Toast.LENGTH_SHORT).show();

                if (isOnReConnect) {
                    WebSocketTool.Connect();
                }

                break;
            case WebSocketTool.TYPE_EXCEPTION:
                Log.e("Message Type", "TYPE_EXCEPTION");
                Toast.makeText(this, "发生异常", Toast.LENGTH_SHORT).show();
                if (!isOnReConnect) {
                    isOnReConnect = true;
                    WebSocketTool.Disconnect();
                }
                break;
            case WebSocketTool.TYPE_DATA: {
                String data = (String) msg.obj;
//                if (message.type == WebSocketTool.TYPE_DATA) {
                boolean found = false;

                List<Book> bookFound = new ArrayList<>();

                for (String key : bookResult.keySet()) {
                    if (data.contains(key)) {
                        bookFound.add(bookResult.get(key));

                        if (!found) {
                            found = true;
                            //answerStr = String.format(stringArray[r.nextInt(stringArray.length)], bookFound.getLocation());
                            data = getString(R.string.book_found);
                        }
                    }
                }

                if (found) {
                    showBookResult(bookFound);
                } else {
                    showNotFoundResult();
                }
//                }
                break;
            }
        }
        return false;
    }

    /**
     * 显示已找到结果页
     */
    private void showBookResult(List<Book> books) {
        Book book = books.get(0);
        book.setSelected(true);

        adapter.setList(books);

        fragment = new BookDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("book", book);
        fragment.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_book_detail, fragment).commit();

        UIHandler.sendEmptyMessage(SHOW_RESULT);
    }

    /**
     * 显示主界面
     */
    private void showHome() {
        llHome.setVisibility(View.VISIBLE);
        llNotFoundResult.setVisibility(View.GONE);
        llFoundResult.setVisibility(View.GONE);
    }

    /**
     * 显示未找到
     */
    public void showNotFoundResult() {
        llHome.setVisibility(View.GONE);
        llFoundResult.setVisibility(View.GONE);
        llNotFoundResult.setVisibility(View.VISIBLE);

        UIHandler.sendEmptyMessageDelayed(RETURN_TO_HOME, RETURN_TO_HOME_DELAY_SHORT);
    }
}
